<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/my/my.css">
    <title>北京自考社区</title>
</head>
<style>
    .showArticle {
        background-color: white;
        box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.04);
        padding: 16px 24px 36px;
        height: auto;
    }
    .article-tool-bar{
        margin-top: -20px;
        margin-left: 4px;
        line-height: 16px;
        font-size: 16px;
    }
    .article-tool-bar a{
        padding: 0px 6px;
    }

    .showArticle .title {
        color: #333;
        margin: 0 0 5px 0;
        font: normal 28px/36px "Microsoft YaHei";
    }

    .showArticle .article_info {
        display: block;
        margin: 0 0 10px 0;
        color: #999;
        font: normal 12px/24px Helvetica, Tahoma, Arial, sans-serif;
    }

    .showArticle p {
        /* height: 24px !important; */
        line-height: 24px !important;
        font-size: 14px;
        font-family: 'Microsoft YaHei', 'SF Pro Display', Roboto, Noto, Arial, 'PingFang SC', sans-serif;
        color: #333;
    }

    .showArticle img {
        width: 100%;
        height: auto;
    }

    .re-layui-inline {
        width: 100%;
        margin-right: 0px !important;
    }

    .my-form-item label, .my-form-item button, .my-form-item textarea {
        display: block;
    }

    .my-form-item label {
        width: 40px;
        line-height: 38px;
        text-align: center;
        padding: 0px;
    }

    .my-form-item textarea {
        width: auto;
        min-width: 780px;
    }

    .my-form-item label, .my-form-item textarea {
        float: left;
    }

    .my-form-item button {
        float: right;
    }

    .remarkShow-item-div {
        border-bottom: 1px solid #E8E8EE;
    }

    /* 子元素全部浮动float,父div没有高度的问题
       可以通过给父div 设置 overflow:hidden来解决
    */
    .remarkShow-item {
        width: 100%;
        overflow: hidden;
    }

    .remarkShow-item label, .remarkShow-item p, .remarkShow-item button {
        display: block;
    }

    .remarkShow-item label {
        width: 40px;
        line-height: 38px;
        text-align: center;
        padding: 0px;
        float: left;
        clear: left;
    }

    .remarkShow-item p {
        line-height: 38px;
        float: left;
    }

    .remarkShow-item button {
        float: right;
    }

    .replyShow {
        margin-left: 40px;
        width: auto;
        overflow: hidden;
    }

    .replyShow label, .replyShow p, .replyShow button {
        display: block;
    }

    .replyShow label {
        width: 40px;
        line-height: 38px;
        text-align: center;
        padding: 0px;
        float: left;
        clear: left;
    }

    .replyShow p {
        line-height: 38px;
        float: left;
    }

    .replyShow button {
        float: right;
    }

    .replyShow-item {
        overflow: hidden;
    }
</style>

<body>
<!-- header -->
<th:block th:include="common::header"></th:block>
<!-- main -->
<div class="layui-container re-layui-container my-main">
    <div class="my-main-content">
        <div class="showArticle" id="showArticle"></div>
        <div class="article-tool-bar">
            <a href="javascript:;" id="praiseIcon"><i class="layui-icon layui-icon-praise"></i><span id="praiseText">点赞</span><span id="praiseNum" th:text="${praiseNum}"></span></a>
            <a href="javascript:;" id="collectIcon"><i class="layui-icon layui-icon-star"></i><span>收藏</span><span id="collectNum" th:text="${collectNum}"></span></a>
            <a href="javascript:;" id="remarkIcon"><i class="layui-icon layui-icon-reply-fill"></i><span>评论</span><span id="remarkNum" th:text="${remarkNum}"></span></a>
        </div>
        <form class="layui-form" style="margin-top: 12px;" lay-filter="remarkForm" action="javascript:;">
            <div class="layui-form-item my-form-item">
                <div class="layui-inline re-layui-inline">
                    <label class="layui-form-label">
                        <i class="layui-icon layui-icon-username" style="font-size: 24px;"></i>
                    </label>
                    <textarea name="remark" id="remark" class="layui-textarea"></textarea>
                    <button lay-submit lay-filter="remarkBtn" class="layui-btn layui-btn-primary my-remark-btn">评论
                    </button>
                </div>
            </div>
        </form>
        <!-- 显示评论 -->
        <div class="remarkShow">
            <div th:each="remarkVo:${remarkVos}" class="remarkShow-item-div">
                <div class="remarkShow-item">
                    <label style="width: auto;">
                        <a href="#" style="padding-right: 6px;" th:text="${remarkVo.user.name} + ':'"></a>
                    </label>
                    <p th:text="${remarkVo.remark.content} +'  '+ ${#dates.format(remarkVo.remark.createTime, 'yyyy-MM-dd hh:mm:ss')}"></p>
                    <!--
                        'javascript:replyBtn(\''+${remark.id}+'\');'
                        thymeleaf模板使用th:onclick进行传参有点特殊，需要这样写才行
                    -->
                    <button th:onclick="'javascript:replyBtn(\''+${remarkVo.remark.id}+'\',0);'"
                            class="layui-btn layui-btn-primary">回复
                    </button>
                </div>
                <!-- 回复按照前后顺序展示就行，不做特别处理 -->
                <div class="replyShow">
                    <div th:id="'reply'+${remarkVo.remark.id}+'-0'"></div>
                    <div th:each="replyVo:${remarkVo.replyVos}" class="replyShow-item">
                        <label style="width: auto;">
                            <a href="#" style="padding-right: 6px;" th:text="${replyVo.user.name} + ':'"></a>
                        </label>
                        <p th:text="${replyVo.reply.content} +'  '+ ${#dates.format(remarkVo.remark.createTime, 'yyyy-MM-dd hh:mm:ss')}"></p>
                        <button th:onclick="'javascript:replyBtn(\''+${remarkVo.remark.id}+'\',\''+${replyVo.reply.id}+'\');'"
                                class="layui-btn layui-btn-primary">回复
                        </button>
                        <div th:id="'reply'+${remarkVo.remark.id}+'-'+${replyVo.reply.id}"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="my-main-side">
        <div class="my-main-side-div">
            <div style="padding: 6px" class="my-adorn-status">
                <p style="font-weight: bold">今日推荐</p>
                <ul id="recomends">

                </ul>
            </div>
            <div style="padding: 6px"  class="my-adorn-recom">
                <p style="font-weight: bold">热门文章</p>
                <ul id="hots">
                </ul>
            </div>
        </div>
    </div>
</div>
<!-- footer -->
<th:block th:include="common::footer"></th:block>
</body>
<script src="/jquery-3.5.1.js"></script>
<script src="/layui/layui.js"></script>
<script src="/my/my.js"></script>

<!--在script中写thymeleaf，一定要带上这一句，不然会出现莫名其妙的错误
    th:inline="javascript" 加上这句后，重新部署项目
-->
<script th:inline="javascript">
    var isPraise = 0;
    var isCollect = 0;

    var articleId = [[${articleId}]];
    var praiseNum = [[${praiseNum}]];
    var remarkNum = [[${remarkNum}]];
    var collectNum = [[${collectNum}]];
    var user = [[${#httpSession.getAttribute('user')}]];

    // 初始化操作 - 页面加载完成执行
    $(document).ready(function () {
        // 渲染文章
        var articleId = [[${articleId}]];
        $.ajax({
            url: '/article/article/info/' + articleId,
            type: 'get',
            contentType: "application/json;charset=UTF-8",
            success: function (obj) {
                var type1 = obj.article.type1;
                var typeStr = "";
                if (type1 == 0){
                    typeStr = "原创";
                }else if (type1 == 1){
                    typeStr = "转载";
                }else if (type1 == 2){
                    typeStr = "翻译";
                }

                $("#showArticle").html("<h1 class='title'>" + obj.article.title + "</h1>")
                    .append("<h4 class='article_info'>发表于: " + new Date(obj.article.createTime).Format("yyyy-MM-dd hh:mm:ss") + " | 作者：" + obj.article.userName + " | " + typeStr + "</h4>")
                    .append(obj.article.content);
            }
        });
        // 渲染今日推荐
        $.ajax({
            url: '/article/article/recommends',
            type: 'get',
            contentType: "application/json;charset=UTF-8",
            success: function (items) {
                var _html = '';
                $.each(items,function (idx,item) {
                    _html += '<li style="margin: 6px 0px;cursor: pointer;"><a href="/article/article/showArticle/'+item.id+'" target="_blank" class="layui-table-link">'+item.title+' </a><img style="width:14px;height: 14px;margin-top: -2px;" src="/images/readCountWhite.png"/>'+ item.pv + '</li>'
                })
                $("#recomends").html(_html);
            },
            error: function () {
                var _html = '<li>数据加载异常</li>';
                $("#recomends").html(_html);
            }
        });
        // 渲染热门文章
        $.ajax({
            url: '/article/article/hots',
            type: 'get',
            contentType: "application/json;charset=UTF-8",
            success: function (items) {
                var _html = '';
                $.each(items,function (idx,item) {
                    _html += '<li style="margin: 6px 0px;cursor: pointer;"><a href="/article/article/showArticle/'+item.id+'" target="_blank" class="layui-table-link">'+item.title+' </a><img  style="width:14px;height: 14px;margin-top: -2px;" src="/images/readCountWhite.png"/>'+ item.totalPv + '</li>'
                })
                $("#hots").html(_html);
            },
            error: function () {
                var _html = '<li>数据加载异常</li>';
                $("#hots").html(_html);
            }
        });
        // 渲染文章工具条
        render_article_tool_bar();
    })
    // 渲染文章工具条
    function render_article_tool_bar(){
        // 渲染点赞
        if (user) {
            var praiseData = {
                "article_id":articleId,
                "user_id":user.id
            }
            $.ajax({
                url: '/article/praise/selectByMap',
                type: 'post',
                contentType: "application/json;charset=UTF-8",
                data: JSON.stringify(praiseData),
                success: function (obj) {
                    if (obj.code == 200 && obj.praiseList.length == 1){
                        $("#praiseText").html("已赞");
                        $("#praiseNum").html(praiseNum);
                        isPraise = 1;
                    }else{
                        $("#praiseText").html("点赞");
                        $("#praiseNum").html(praiseNum);
                        isPraise = 0;
                    }
                }
            });
        }
        // 渲染收藏
        if (user) {
            var collectData = {
                "article_id":articleId,
                "user_id":user.id
            }
            $.ajax({
                url: '/article/collect/selectByMap',
                type: 'post',
                contentType: "application/json;charset=UTF-8",
                data: JSON.stringify(collectData),
                success: function (obj) {
                    if (obj.code == 200 && obj.collectList.length == 1){
                        $("#collectIcon i").removeClass("layui-icon-star");
                        $("#collectIcon i").addClass("layui-icon-star-fill");
                        $("#collectNum").html(collectNum);
                        isCollect = 1;
                    }else{
                        $("#collectIcon i").removeClass("layui-icon-star-fill");
                        $("#collectIcon i").addClass("layui-icon-star");
                        $("#collectNum").html(collectNum);
                        isCollect = 0;
                    }
                }
            });
        }
    }

    layui.use(['form', 'layedit', 'layer','element','util'], function () {
        var element = layui.element;
        var util = layui.util;
        var form = layui.form;
        var layer = layui.layer;
        var $ = layui.jquery;

        // 页面固定块
        util.fixbar({
            bar1: '&#xe611'
            ,css: {
                right: 50,
                bottom: 100
            }
            ,bgcolor: '#393D49'
            ,click: function(type){
                // 评论
                if (type === 'bar1'){
                    var user = [[${#httpSession.getAttribute('user')}]];
                    if (!user) {
                        alert("请先登录");
                    }else{
                        $("#remark").focus();
                    }
                }
            }
        });

        // 监听点赞图标
        $(document).on('click','#praiseIcon',function(){
            if (!user) {
                layer.open({
                    type: 0,
                    content: "登录后才能点赞"
                });
                return;
            }

            var praiseData = {
                "articleId":articleId,
                "userId":user.id
            };
            if (!isPraise){
                $.ajax({
                    url: '/article/praise/save',
                    type: 'post',
                    contentType: "application/json;charset=UTF-8",
                    data: JSON.stringify(praiseData),
                    success: function (obj) {
                        if (obj.code == 200){
                            praiseNum += 1;
                            render_article_tool_bar();
                        }
                    }
                });
            }else{
                $.ajax({
                    url: '/article/praise/removeObj',
                    type: 'post',
                    contentType: "application/json;charset=UTF-8",
                    data: JSON.stringify(praiseData),
                    success: function (obj) {
                        if (obj.code == 200){
                            praiseNum -= 1;
                            render_article_tool_bar();
                        }
                    }
                });
            }
        });

        // 监听评论图标
        $(document).on('click','#remarkIcon',function(){
            var user = [[${#httpSession.getAttribute('user')}]];
            if (!user) {
                alert("请先登录");
            }else{
                $("#remark").focus();
            }
        });

        // 监听收藏图标
        $(document).on('click','#collectIcon',function(){
            var user = [[${#httpSession.getAttribute('user')}]];
            if (!user) {
                layer.open({
                    type: 0,
                    content: "登录后才能收藏"
                });
                return;
            }

            var collectData = {
                "articleId":articleId,
                "userId":user.id
            };
            if (!isCollect){
                $.ajax({
                    url: '/article/collect/save',
                    type: 'post',
                    contentType: "application/json;charset=UTF-8",
                    data: JSON.stringify(collectData),
                    success: function (obj) {
                        if (obj.code == 200){
                            collectNum += 1;
                            render_article_tool_bar();
                        }
                    }
                });
            }else{
                $.ajax({
                    url: '/article/collect/removeObj',
                    type: 'post',
                    contentType: "application/json;charset=UTF-8",
                    data: JSON.stringify(collectData),
                    success: function (obj) {
                        if (obj.code == 200){
                            collectNum -= 1;
                            render_article_tool_bar();
                        }
                    }
                });
            }
        });

        // 监听评论输入框
        $(document).on('focus','#remark',function(){
            var user = [[${#httpSession.getAttribute('user')}]];
            if (!user) {
                alert("请先登录");
                $("#remark").blur();
            }
        });

        // 监听评论提交
        form.on('submit(remarkBtn)', function (data) {
            var remarkForm = form.val("remarkForm");
            var userId = user.id;
            var remarkData = {
                "content": remarkForm.remark,
                "articleId": articleId,
                "userId": userId
            }

            if(remarkForm.remark == ''){
                layer.open({
                    type: 0,
                    content: "请输入评论内容"
                });
                return;
            }

            $.ajax({
                url: '/article/remark/save',
                type: 'post',
                contentType: "application/json;charset=UTF-8",
                data: JSON.stringify(remarkData),
                success: function (obj) {
                    if (obj.code == 200){
                        layer.open({
                            type: 0,
                            content: "评论成功"
                        });
                    }else{
                        layer.open({
                            type: 0,
                            content: "评论失败"
                        });
                    }

                }
            });
            window.location.reload();
        });

        // 监听回复提交
        form.on('submit(replyBtn)', function (data) {
            var replyForm = form.val("replyForm");
            var remarkId = replyBtn_p1;
            var userId = 1;
            var replyData = {
                "content": replyForm.reply,
                "remarkId": remarkId,
                "userId": userId
            }

            if(replyForm.reply == ''){
                layer.open({
                    type: 0,
                    content: "请输入回复内容"
                });
                return;
            }

            $.ajax({
                url: '/article/reply/save',
                type: 'post',
                contentType: "application/json;charset=UTF-8",
                data: JSON.stringify(replyData),
                success: function (obj) {
                    if (obj.code == 200){
                        layer.open({
                            type: 0,
                            content: "回复成功"
                        });
                    }else{
                        layer.open({
                            type: 0,
                            content: "回复失败"
                        });
                    }
                }
            });
            window.location.reload();
        });
    });

    // 一个页面定时器,用于统计pv
    var timeoutId = setTimeout(function () {
        var articleId = [[${articleId}]];
        $.get('/article/article/statistics/pv/' + articleId, function (data, status) {
            console.log("Data: " + data + "\nStatus: " + status);
        });
    }, 10000);

    // 声明2个变量，用于保存replyBtn函数每次的调用参数
    var replyBtn_p1 = null;
    var replyBtn_p2 = null;
    // 点击回复按钮调用函数
    function replyBtn(p1, p2) {
        console.log("replyBtn_p1:", replyBtn_p1, ",replyBtn_p2:", replyBtn_p2, ",p1:", p1, ",p2:", p2);
        // 如果用户多次点击回复按钮，则要进行额外处理
        if (replyBtn_p1 == p1 && replyBtn_p2 == p2) {
            $("#reply" + replyBtn_p1 + "-" + replyBtn_p2).empty();
            replyBtn_p1 = null;
            replyBtn_p2 = null;
            return;
        }

        if (replyBtn_p1 && replyBtn_p2 >= 0) {
            $("#reply" + replyBtn_p1 + "-" + replyBtn_p2).empty();
        }

        replyBtn_p1 = p1;
        replyBtn_p2 = p2;
        $("#reply" + p1 + "-" + p2)
            .html("<form class=\"layui-form\" style=\"margin-top: 12px;\" lay-filter=\"replyForm\" action=\"javascript:;\">"
                + "<div class=\"layui-form-item my-form-item\">"
                + "<div class=\"layui-inline re-layui-inline\">"
                + "<label class=\"layui-form-label\">"
                + "<i class=\"layui-icon layui-icon-username\" style=\"font-size: 24px;\"></i>"
                + "</label>"
                + "<textarea style='min-width: 740px' name=\"reply\" id=\"reply\" class=\"layui-textarea\"></textarea>"
                + "<button lay-submit lay-filter=\"replyBtn\" class=\"layui-btn layui-btn-primary my-remark-btn\">确定</button>"
                + "</div>"
                + "</div>"
                + "</form>");
    }
</script>

</html>